<template>
  <div class="network_type_tab_panel" v-loading="loading" element-loading-text="加载中...">
    <div class="header">
      <div class="btn_group">
        <HPlainButton @click="addNetworkTypeDialogVisible = true">添加分类</HPlainButton>
        <el-dropdown trigger="click">
          <HButton :disabled="selecttion.length == 0">
            批量操作
            <el-icon class="el-icon--right">
              <arrow-down />
            </el-icon>
          </HButton>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="changeAll(1)">
                <el-icon>
                  <CircleCheck />
                </el-icon>
                批量启用
              </el-dropdown-item>
              <el-dropdown-item @click="changeAll(2)">
                <el-icon>
                  <Warning />
                </el-icon>
                批量禁用
              </el-dropdown-item>
              <el-dropdown-item @click="changeAll(3)">
                <el-icon>
                  <Delete />
                </el-icon>
                批量删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
    <div class="table">
      <el-table
        border
        stripe
        resizable
        @selection-change="handleChange"
        ref="tableRef"
        :data="tableData"
        :tree-props="{ children: 'childData' }"
        height="100%"
        row-key="id"
      >
        <el-table-column type="selection" width="40" fixed="left" :align="'center'" />
        <el-table-column type="index" label="序号" width="50" fixed="left" :align="'center'" />
        <el-table-column show-overflow-tooltip prop="name" label="网点分类名称" min-width="150" />
        <el-table-column show-overflow-tooltip prop="createTime" label="创建时间" width="170" />
        <el-table-column show-overflow-tooltip prop="updateTime" label="更新时间" width="170" />
        <el-table-column prop="name" label="状态" width="70" fixed="right" :align="'center'">
          <template #default="scope">
            <HStatus v-if="scope.row.status" type="info">禁用</HStatus>
            <HStatus v-else>启用</HStatus>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="160">
          <template #default="scope">
            <el-space
              :size="0"
              :spacer="dividerIcon"
              style="display: flex; justify-content: flex-end"
            >
              <h-link v-if="scope.row.level != 3" @click="handleAddChildrenGrade(scope.row)"
                >添加子类</h-link
              >
              <HLink @click="handleEditType(scope.row.id)">编辑</HLink>
              <h-link type="error" @click="handleDelNetworkType(scope.row)">删除</h-link>
            </el-space>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <AddNetworkType
      v-model:visible="addNetworkTypeDialogVisible"
      type="network"
      @update="getList"
    />

    <AddChildNetworkType
      v-model:visible="addChildNetworkTypeDialogVisible"
      type="network"
      @update="getList"
      :parent-type="currentAddChildTypeNetyworkType"
    />

    <UpdateNetworkType
      v-model:visible="updateNetworkTypeDialogVisible"
      type="network"
      @update="getList"
      :update-type="currentUpdateNetworkType"
    />
  </div>
</template>

<script setup lang="ts">
  import { ref, h } from 'vue'
  import type { TableInstance } from 'element-plus'
  import { ElDivider, ElMessage, ElMessageBox } from 'element-plus'
  import { Delete, Warning, ArrowDown, CircleCheck } from '@element-plus/icons-vue'
  import { getTypeList, disableType, deleteType } from '@/api/basic'
  import { AddOrUpdateNetworkTypeFrom, NetworkType } from './types'
  import { useGetNetworkTypeDetail } from './services'
  import AddNetworkType from '@/components/pages/common/type/add-type/AddType.vue'
  import AddChildNetworkType from '@/components/pages/common/type/add-child-type/AddChildType.vue'
  import UpdateNetworkType from '@/components/pages/common/type/update-type/UpdateType.vue'
  import { UpdateNetworkTypeProps } from '@/components/pages/common/type/update-type/types'

  // 添加分类弹窗显示状态
  const addNetworkTypeDialogVisible = ref(false)

  // 添加子类弹窗显示状态
  const addChildNetworkTypeDialogVisible = ref(false)

  // 编辑分类弹窗显示状态
  const updateNetworkTypeDialogVisible = ref(false)

  // 当前正在添加子类的父类
  const currentAddChildTypeNetyworkType = ref({
    id: '',
    name: '',
    parentId: '',
    status: false,
    level: 1,
  })

  /**
   * 添加下级按钮点击事件
   * @param {object} networkType - 网点分类
   */
  const handleAddChildrenGrade = (networkType: NetworkType) => {
    currentAddChildTypeNetyworkType.value = {
      id: networkType.id,
      name: networkType.name,
      parentId: networkType.parentId,
      status: networkType.status,
      level: networkType.level,
    }
    addChildNetworkTypeDialogVisible.value = true
  }

  // 当前正在编辑的分类
  const currentUpdateNetworkType = ref<UpdateNetworkTypeProps>({
    id: '',
    name: '',
    parentId: '',
    status: false,
    level: 1,
  })

  /**
   * 编辑分类
   * @param id
   */
  const handleEditType = async (id: string) => {
    await getNetworkTypeDetail(id)
    currentUpdateNetworkType.value = {
      id: networkTypeDetail.value.id,
      name: networkTypeDetail.value.name,
      parentId: networkTypeDetail.value.parentId,
      status: networkTypeDetail.value.status,
      level: networkTypeDetail.value.level,
    }
    updateNetworkTypeDialogVisible.value = true
  }

  const { networkTypeDetail, getNetworkTypeDetail } = useGetNetworkTypeDetail()

  const tableRef = ref<TableInstance | null>(null)
  const addDialogVisible = ref(false)
  const dividerIcon = h(ElDivider, {
    direction: 'vertical',
    style: 'display: flex; align-items: center;',
  })
  const form = ref<AddOrUpdateNetworkTypeFrom>({
    name: '',
    status: false,
  })

  /**
   * 删除网点分类
   * @param networkType - 网点分类
   */
  const handleDelNetworkType = (networkType: NetworkType) => {
    if (tableRef.value) {
      tableRef.value.clearSelection()
      tableRef.value.toggleRowSelection(networkType, true)
      changeAll(3)
    }
  }

  const tableData = ref([]) // 列表数据

  const total = ref() // 总数目
  const loading = ref(false)

  // 获取表格选中的数据
  const selecttion = ref([])
  const handleChange = (val: any[]) => {
    if (val.length != 0) {
      val.forEach((item: { id: any }) => {
        if (Object.values(selecttion.value).indexOf(item.id) == -1) {
          selecttion.value.push(item.id)
        } else {
          selecttion.value = selecttion.value.filter((i) => i == item.id)
        }
      })
    } else {
      selecttion.value = []
    }
  }

  // 获取列表数据
  const getList = async () => {
    loading.value = true
    await getTypeList().then((res) => {
      tableData.value = res.data.data.rows
      total.value = parseInt(res.data.data.total)
    })
    loading.value = false
  }

  // 批量操作的方法
  const changeMethod = (type, method, arr, status, dialog) => {
    if (arr.length == 0) {
      ElMessage({
        message: `请选择要${type}的分类`,
        type: 'warning',
        duration: 5000,
        plain: true,
        showClose: true,
      })
      return
    }
    ElMessageBox({
      type: type === '删除' ? 'error' : 'warning',
      title: '提示',
      message: `确认${type}选中的分类?`,
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      autofocus: false,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '加载中...'
          setTimeout(() => {
            done()
            setTimeout(() => {
              instance.confirmButtonLoading = false
            }, 0)
          }, 1000)
        } else {
          done()
        }
      },
    }).then(async () => {
      if (status != 3) {
        await method(arr, status).then((res) => {
          ElMessage({
            message: res.data.message,
            type: res.data.success ? 'success' : 'error',
            duration: 5000,
            plain: true,
            showClose: true,
          })
        })
      } else {
        await method(arr).then((res) => {
          ElMessage({
            message: res.data.message,
            type: res.data.success ? 'success' : 'error',
            duration: 5000,
            plain: true,
            showClose: true,
          })
          if (dialog != '') {
            dialog.value = false
          }
        })
      }
      tableRef.value.clearSelection()
      getList()
    })
  }

  // 修改类型状态
  const changeAll = (n) => {
    if (n == 1) {
      changeMethod('启用', disableType, selecttion.value, false, '')
    }
    if (n == 2) {
      changeMethod('禁用', disableType, selecttion.value, true, '')
    }
    if (n == 3) {
      changeMethod('删除', deleteType, selecttion.value, 3, '')
    }
    if (n == 33) {
      changeMethod('删除', deleteType, [form.value.id], 3, addDialogVisible)
    }
  }

  // 返回方法
  defineExpose({ getList })
</script>

<style scoped lang="scss">
  @import './NetworkTypeTabPanel.scss';
</style>
